import { getSingerList } from '@/api/singer'
import type { ComputedRef, Ref, UnwrapRef } from 'vue'

interface ISinger {
  title: string
  list: ISingerItem[]
}
export default function useCurrentSectionTitle(): {
  groupRef: Ref<UnwrapRef<HTMLUListElement | null>>
  singerList: Ref<ISinger[]>
  currentTitle: ComputedRef<string>
  currentIndex: Ref<number>
  currentTitleStyle: ComputedRef<{ transform: string }>
  indexList: ComputedRef<string[]>
  scrollHandle: (pos: IPos) => void
} {
  const TITLE_HEIGHT = 30
  const singerList = ref<ISinger[]>([])
  const heights = ref<number[]>([])
  const scrollY = ref<number>(0)
  const distance = ref<number>(0)
  const groupRef = ref<HTMLUListElement | null>(null)
  const currentIndex = ref<number>(0)
  const currentTitle = computed<string>(() => {
    if (scrollY.value < 0) {
      return ''
    }
    const current = singerList.value[currentIndex.value]
    return current ? current.title : ''
  })
  const currentTitleStyle = computed<{ transform: string }>(() => {
    const distanceVal = distance.value
    const different = distanceVal > 0 && distanceVal < TITLE_HEIGHT ? distanceVal - TITLE_HEIGHT : 0
    return {
      transform: `translate3d(0,${different}px,0)`
    }
  })
  const indexList = computed<string[]>(() => {
    return singerList.value?.map((item) => item.title) || []
  })
  onMounted(async () => {
    singerList.value = (await getSingerList()).data
  })
  watch(singerList, async () => {
    await nextTick()
    calculatorHeights()
  })
  watch(scrollY, (newVal: number) => {
    const heightsVal = heights.value
    for (let i = 0; i < heightsVal.length - 1; i++) {
      const prevHeight = heightsVal[i]
      const nextHeight = heightsVal[i + 1]
      if (newVal >= prevHeight && newVal <= nextHeight) {
        currentIndex.value = i
        distance.value = nextHeight - newVal
      }
    }
  })
  function calculatorHeights() {
    let height = 0
    const length = groupRef.value?.children.length || 0
    const heightsVal = heights.value
    heightsVal.length = 0
    heightsVal.push(height)
    for (let i = 0; i < length; i++) {
      height += groupRef.value!.children[i].clientHeight
      heightsVal.push(height)
    }
  }
  function scrollHandle(pos: IPos) {
    scrollY.value = -pos.y
  }

  return {
    groupRef,
    singerList,
    currentTitle,
    currentIndex,
    indexList,
    currentTitleStyle,
    scrollHandle
  }
}
